<!-- 2024-12-19 生产工单-复制BOM版本 按钮弹框 -->
<template>
  <el-dialog :title="title" :visible.sync="open" width="90%" append-to-body @close="cancel">
    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane label="根据原工单修改" name="first">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
          label-width="68px">
          <el-form-item label="工单编号" prop="workorderCode">
            <el-input v-model="queryParams.workorderCode" placeholder="请输入工单编号" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>

          <!-- add begin by zyj 2024/10/18 -->
          <el-form-item label="工单类型" prop="orderType">
            <el-select v-model="queryParams.orderType" placeholder="请选择工单类型" clearable
              @keyup.enter.native="handleQuery">
              <el-option v-for="item, index in dict.type.mes_order_type" :key="index" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <!-- add end by zyj 2024/10/18 -->
          <el-form-item label="流程状态" prop="workflowStatus">
            <el-select v-model="queryParams.workflowStatus" placeholder="请选择流程状态" clearable>
              <el-option v-for="dict in dict.type.workflow_status" :key="dict.value" :label="dict.label"
                :value="Number(dict.value)"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="产品编号" prop="productCode">
            <el-input v-model="queryParams.productCode" placeholder="请输入产品编号" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="产品名称" prop="productName">
            <el-select filterable clearable placeholder="请输入产品名称" v-model="queryParams.productName"
              @keyup.enter.native="handleQuery" remote @clear="onClearProductName" :loading="productNameListLoading"
              :remote-method="remoteGetProductNameList">
              <el-option v-for="(item, index) in productNameList" :key="index" :label="item" :value="item"></el-option>
            </el-select>
            <!-- edit end by zyj 2024/10/17 产品名称支持模糊搜索下拉-->
          </el-form-item>
          <el-form-item label="单据日期" prop="fDate">
            <el-date-picker clearable v-model="queryParams.fDate" type="date" value-format="yyyy-MM-dd"
              placeholder="请选择需求日期"></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-table v-loading="loading" :data="workorderList" row-key="workorderId" default-expand-all
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" height="calc(45vh)"
          @current-change="handleCurrentChange">
          <el-table-column type="radio" width="55">
            <template slot-scope="scope">
              <el-radio :label="scope.row.workorderId" v-model="selectedId"
                @change.native="handleCurrentChange(scope.row)">{{ '' }}</el-radio>
            </template>
          </el-table-column>
          <el-table-column label="序号" align="center" width="50px">
            <template slot-scope="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="生产工单id" align="center" prop="workorderId" width="110"></el-table-column>
          <el-table-column label="工单编号" align="center" prop="billNo" width="110"></el-table-column>
          <el-table-column label="单据日期" align="center" prop="fDate" width="160"></el-table-column>
          <el-table-column label="类型" align="center" prop="orderType">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.mes_order_type" :value="scope.row.orderType" />
            </template>
          </el-table-column>
          <el-table-column label="工单状态" align="center" prop="status">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.mes_workorder_status" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column label="流程状态" align="center" prop="workflowStatus">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.workflow_status" :value="scope.row.workflowStatus" />
            </template>
          </el-table-column>
          <el-table-column label="物料编码" width="150" align="center" prop="productCode" />
          <el-table-column label="物料名称" width="180" align="center" prop="productName" :show-overflow-tooltip="true" />
          <el-table-column label="规格型号" width="220" align="center" prop="productSpc" :show-overflow-tooltip="true" />
          <el-table-column label="单位" align="center" prop="unitName" />
          <el-table-column label="工单数量" align="center" prop="quantity" />
          <el-table-column label="已生产数量" align="center" width="100px" prop="quantityProduced" />
          <el-table-column label="批次号" align="center" min-width="220px">
            <template slot-scope="scope">
              <span v-if="scope.row.batchName != null">{{
                scope.row.batchName
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="领料状态" align="center" width="100px">
            <template slot-scope="scope">
              <span>
                {{
                  scope.row.isIssue == "0"
                    ? "未领料"
                    : scope.row.isIssue == "1"
                      ? "全部领料"
                      : scope.row.isIssue == "2"
                        ? "部分领料"
                        : "--"
                }}
              </span>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" :page-sizes="[50, 100, 200, 300, 400, 500]" @pagination="getList" />

      </el-tab-pane>
      <el-tab-pane label="直接修改" name="second">
        <el-form :model="form" ref="form" size="small" :inline="true" :rules="rules"
          style="margin: 0 auto;text-align: center;">
          <el-form-item label="BOM版本" prop="bomItemCode">
            <!-- <el-input v-model="form.bomItemCode" placeholder="请输入BOM版本" clearable /> -->
            <el-select size="mini" v-model="form.bomItemCode" allow-create default-first-option filterable
              @change="WOStatusChange" placeholder="请选择BOM版本">
              <el-option v-for="item in dataArray" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submitFormBtn" :loading="submitLoading">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { listWorkorder, getProductNameList, modifyBomItemCode, directLyModifyBomItemCode } from "@/api/mes/pro/workorder";
export default {
  name: "copyBom",
  dicts: [
    "mes_workorder_status",
    "mes_order_status",
    "mes_order_type",
    "mes_workorder_sourcetype",
    "mes_workorder_runStatus",
    "mes_route_status",
    "workflow_status",
  ],
  data() {
    return {
      title: "复制BOM版本",
      open: false,
      rowInfo: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        workorderCode: null,
        workorderId: null,
        workorderName: null,
        orderSource: null,
        sourceCode: null,
        productId: null,
        productCode: null,
        productName: null,
        productSpc: null,
        unitOfMeasure: null,
        quantity: null,
        quantityProduced: null,
        quantityChanged: null,
        quantityScheduled: null,
        clientId: null,
        clientCode: null,
        clientName: null,
        requestDate: null,
        parentId: null,
        ancestors: null,
        //add begin by zyj 2024/10/17 查询条件增加类型
        orderType: null,
        //add end by zyj 2024/10/17 查询条件增加类型
        status: null,
        workflowStatus: null,
        fDate: null,
      },
      // 显示搜索条件
      showSearch: true,
      //add begin by zyj 2024/10/17 产品名称支持模糊搜索下拉
      productNameList: [],
      //add end by zyj 2024/10/17 产品名称支持模糊搜索下拉
      productNameListLoading: false,
      // 生产工单表格数据
      loading: true,
      total: 0,
      workorderList: [],
      selectedId: null,
      currentRow: {},
      // 生产工单表格数据  end
      activeName: 'first',
      form: { bomItemCode: null },//直接修改form
      submitLoading: false,
      // 表单校验
      rules: {
        bomItemCode: [
          {
            required: true,
            message: "BOM版本不能为空",
            trigger: "blur",
          },
        ],
      },
      dataArray: [{ label: 'MES通用版BOM', value: 'MES通用版BOM' }]
    };
  },
  watch: {
    'checkedRemakeSN': {
      handler(val) {
        if (this.checkedOldSN && val) {
          this.dataList = this.mergeTwoArrIntoOneArr(this.checkedOldSN, val)
        }

      },
      immediate: true
    },
    'checkedOldSN': {
      handler(val) {
        if (val && this.checkedRemakeSN) {
          this.dataList = this.mergeTwoArrIntoOneArr(val, this.checkedRemakeSN)
        }
      },
      immediate: true
    }
  },
  methods: {
    /* 2024-12-26 djj 增加两个TAB项，根据原工单修改、直接修改 */
    handleClick(tab, event) {
      console.log(tab, event);
    },
    /**
     *
     * @param arr1  oldSnCode
     * @param arr2  remardkSnCode 改制
     */
    mergeTwoArrIntoOneArr(arr1, arr2) {
      let arr = [];
      if (arr1.length > arr2.length) {
        arr = arr1.map((item, index) => { return { oldSnCode: item, remakeSnCode: arr2[index] ? arr2[index] : '' } })
      } else {
        arr = arr2.map((item, index) => { return { oldSnCode: arr1[index] ? arr1[index] : '', remakeSnCode: item } })
      }
      return arr;
    },
    //初始化函数
    init(row) {
      this.activeName == 'first'
      this.rowInfo = row
      this.open = true;
      this.getList();
    },
    //add begin by zyj 2024/10/17 产品名称支持模糊搜索下拉
    onClearProductName() {
      this.remoteGetProductNameList();
    },
    remoteGetProductNameList(productName) {
      this.productNameListLoading = true;
      getProductNameList({ productName: productName }).then(res => {
        this.productNameList = res.data;
        this.productNameListLoading = false;
      })
    },
    //add end by zyj 2024/10/17 产品名称支持模糊搜索下拉
    toWorkingRecord(row) {
      this.$refs.worktimerecord.handleAddRecord(row.workorderId);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 查询生产工单列表 */
    getList() {
      if (!this.rowInfo['workorderId']) {
        return false
      }
      this.loading = true;
      listWorkorder({ ...this.queryParams, remakeWorkorderId: this.rowInfo.workorderId }).then((response) => {
        this.workorderList = this.handleTree(
          response.rows,
          "workorderId",
          "parentId"
        );
        this.total = response.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    /* 选择新生产工单 */
    handleCurrentChange(row) {
      if (!row) {
        this.selectedId = null
        this.currentRow = {}
        return
      }
      this.selectedId = row.workorderId
      this.currentRow = row
    },

    /* 取消按钮 */
    cancel() {
      this.open = false;
      this.selectedId = null
      this.currentRow = {}
      this.form = {}
      this.queryParams = {}
      this.activeName == 'first'
    },
    /** 提交按钮 */
    submitFormBtn() {
      console.info(this.activeName)
      if (this.activeName == 'first') {
        this.submitForm()
      }
      if (this.activeName == 'second') {
        this.submitForm2()
      }
    },
    /** 根据原工单复制BOM版本 */
    submitForm() {
      if (!this.selectedId) {
        this.$message.warning("请选择要复制的工单")
        return
      }
      this.submitLoading = true;
      let param = {}
      param = {
        oldWorkorderId: this.selectedId,
        remakeWorkorderId: this.rowInfo.workorderId,
      }
      modifyBomItemCode({ ...param }).then((res) => {
        this.$message.success("保存成功");
        this.submitLoading = false;
        this.cancel();
      }).catch(() => {
        this.submitLoading = false;
      });
    },
    /** 直接修改复制BOM版本 */
    submitForm2() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          let param = {}
          param = {
            bomItemCode: this.form.bomItemCode,
            remakeWorkorderId: this.rowInfo.workorderId,
          }
          directLyModifyBomItemCode({ ...param }).then((res) => {
            this.$message.success("保存成功");
            this.submitLoading = false;
            this.cancel();
          }).catch(() => {
            this.submitLoading = false;
          });
        }
      })

    },
  }
}
</script>
<style lang='scss' scoped>
.dialog-footer {
  padding-top: 20px;
  text-align: center;
}

.sn-title {
  background-color: #ddd;
  padding: 10px;
  box-sizing: border-box;
  margin-bottom: 10px;
}

.sn-title :deep(.el-checkbox .el-checkbox__label) {
  color: #fff !important;
}
</style>
